package rabbitmq.test.dlx;

import com.rabbitmq.client.*;
import org.junit.Before;
import org.junit.Test;

import java.nio.charset.StandardCharsets;

/**
 * 专门消费监听的测试类
 */
public class DlxBizConsumer {
    private Channel channel;
    @Before
    public void init(){
        //1.创建长连接 提供属性(ip,port,username,password,virtualHost)
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.8.100");
        factory.setPort(5672);//TCP协议端口
        factory.setUsername("admin");
        factory.setPassword("123456");
        factory.setVirtualHost("/");
        try{
            Connection connection = factory.newConnection();
            //2.从长连接赋值短链接
            channel=connection.createChannel();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("创建连接失败");
        }
    }
    //测试消费逻辑代码 只处理reject 并且不设置requeue重新投入队列
    @Test
    public void bizConsume() throws Exception{
        DeliverCallback deliver= (consumerTag, message) -> {
            byte[] body = message.getBody();
            String msg=new String(body, StandardCharsets.UTF_8);
            System.out.println("业务消费收到的消息:"+msg);
            //以拒绝的方式 将消息变成死信
            channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
        };
        CancelCallback cancel= consumerTag -> {
            //当消费者取消消费的时候 cancel会调用 channel.basicCancel();
            System.out.println("消费者取消消费");
        };
        channel.basicConsume(DlxDeclare.BIZ_QUEUE,
                false,
                deliver,
                cancel);
        while(true);
    }
}
